<?php

class Wikipedia {

    public $file = 'data/wikipedia/wikipedia.tmp';

    public $url ='http://en.wikipedia.org/wiki/List_of_albums_released_in_2010';

    public function getReleases() {

        if(!file_exists($this->file)) {

            $f = fopen($_SERVER['DOCUMENT_ROOT'].$this->file, 'w');

            $data = file_get_contents($this->url);

            fwrite($f, $data);
            fclose($f);

        } else {

            $data = file($_SERVER['DOCUMENT_ROOT'].$this->file, FILE_USE_INCLUDE_PATH);
        }

        $tba = false;
        $date = null;

        $result = array();

        foreach($data as $n => $line) {
            if(preg_match('/\<b\>(january|february|march|april|may|june|july|august|september|october|november|december)\ (\d+)\<\/b\>/i', $line, $m)) {
                $date = date('Y-m-d', strtotime(strip_tags($m[0])));

            }

            if(strpos($line, 'date undetermined') !== false && !empty($date)) {
                $tba = true;
            }

            if(preg_match('/\<li\>(.+)\ by\ (.*)\<\/li\>/i', $line, $m)) {

                $release_data = strip_tags($m[0]);

                $release_data = preg_replace('/\[(\d+)\]/', '', $release_data);

                list($release, $artist) = explode('by', $release_data, 2);
                
                if($tba)
                    $date = date('Y');

                $result[] = array(
                    'date'=>trim($date),
                    'artist'=>trim($artist),
                    'release'=>trim($release));
            }
        }

        return $result;

    }

}